package service.impl;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import pojo.User;
import redis.clients.jedis.Jedis;
import service.UserService;
import util.JavaMailUtil;
import util.JedisUtil;

import java.util.UUID;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    @Override
    public boolean add(User user) {
        return userDao.add(user)>0;
    }

    @Override
    public User login(String account, String password) {
        User user = userDao.findByAccount(account);
        if (user == null) {
            return null;
        }

        if (!password.equals(user.getPassword())) {
            return null;
        }

        return user;
    }

    @Override
    public boolean registerByEmail(User user) {
        try {
            /**
             *  新增用户
             */
            add(user);

            /**
             * 生成激活码，存到redis
             */
            //随机生成激活码
            String code = UUID.randomUUID().toString();
            Jedis jedis = JedisUtil.getJedis();
            jedis.setex("register::"+user.getEmail(), 300, code);
            JedisUtil.closeJedis(jedis);

            /**
             * 发送邮件
             */
            //邮件标题
            String title = "地表最强demo邮箱验证";
            //邮件内容
            String content = "<html><head></head><body><h1>请点击链接激活</h1><h3>"
                    + "<a href='http://localhost:8080/pay_demo/UserServlet?"
                    + "action=active&account="+user.getEmail()
                    +"&code="+ code + "'>点我激活</a></h3></body></html>";

            JavaMailUtil.sendEmail(user.getEmail(), content, title);

            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public boolean active(String account, String code) {
        String key = "register::"+account;
        Jedis jedis = JedisUtil.getJedis();

        if(!jedis.exists(key)){
            return false;
        }

        String value = jedis.get(key);

        if (!value.equals(code)) {
            return false;
        }

        User user = userDao.findByAccount(account);

        if (user.getStatus() != 0) {
            return false;
        }


        user.setStatus(1); //设为激活状态

        userDao.update(user);

        jedis.del(key);

        JedisUtil.closeJedis(jedis);

        return true;
    }
}
